package com.chj.nettydemo.direct.channel;

import com.chj.nettydemo.direct.handler.Gb32ServerHandler;
import com.chj.nettydemo.properties.NettyServerProperties;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class Gb32ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Resource
    NettyServerProperties nettyServerProperties;

    @Resource
    Gb32ServerHandler gb32ServerHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline().addFirst(new IdleStateHandler(0, 0, nettyServerProperties.getKeepAlive(), TimeUnit.SECONDS));
        //添加编解码 针对于 gb32
        // https://blog.csdn.net/zougen/article/details/79037675
//        socketChannel.pipeline().addLast("in-decoder", new LengthFieldBasedFrameDecoder(6 * 1024, 22, 2, 1, 0));
        socketChannel.pipeline().addLast("in-decoder-step1", new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("$".getBytes())));
        socketChannel.pipeline().addLast("in-decoder-step2", new StringDecoder(StandardCharsets.UTF_8));
        //添加编码器
        socketChannel.pipeline().addLast("out-encoder", new StringEncoder(StandardCharsets.UTF_8));
        socketChannel.pipeline().addLast(gb32ServerHandler);
    }
}